<?php
/*

Plugin Name: basket_mail

Plugin URI: 

Description: basket mail

Version: 1.0

Author: 1625.me 

Author URI: 

*/



//register_taxonomy( 'classification', 'post', array( 'hierarchical' => true, 'label' => 'Classification', 'query_var' => true, 'rewrite' => array( 'slug' => 'genre' ) , 'show_in_nav_menus' => true , 'show_ui' => true) );







session_start();
global $plugin_version,$favorite_mail_cookie,$table_mail_post_rel,$table_mail_content,$wpdb;
$table_mail_post_rel = $wpdb->prefix . 'favorite_mail_post_rel';
$table_mail_content = $wpdb->prefix . 'favorite_mail_content';
$plugin_version = "1.2";

register_activation_hook( __FILE__, 'favorite_mail_install'); // starts the installation of the database if the plugin is activated
add_action('admin_menu', 'favorite_mail_menu');
add_action( 'init', 'create_post_type' );
function create_post_type() {
	register_post_type( 'acme_product',
		array(
			'labels' => array(
				'name' => __( 'Products' ),
				'singular_name' => __( 'Product' )
			),
			'public' => true,
			'has_archive' => true,
			'rewrite' => array('slug' => 'products')
		)
	);
}



function favorite_mail_install() {

global $wpdb,$table_mail_post_rel,$table_mail_content;



# Create DB table

$sql = "CREATE TABLE IF NOT EXISTS $table_mail_post_rel (
	    MAIL_REL_ID INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
	    POST_ID BIGINT(20) NULL,
	    MAIL_ID INT(11) NULL,
	    USER_ID MEDIUMINT NULL,
	    COOKIE TEXT NULL,
	    UNIQUE KEY MAIL_REL_ID (MAIL_REL_ID)
	    ) TYPE = MYISAM  DEFAULT CHARSET=utf8;";
$result = $wpdb->query($sql);

$sql2 = "CREATE TABLE IF NOT EXISTS $table_mail_content (
 		MAIL_ID BIGINT(11) NOT NULL AUTO_INCREMENT,
 		CREATED_DATE timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ,
 		IP VARCHAR(50) NOT NULL DEFAULT '',
 		NAME VARCHAR(50) NOT NULL DEFAULT '',
 		EMAIL VARCHAR(100) NOT NULL DEFAULT '',
		CONTENT TEXT NULL,
  		UNIQUE KEY MAIL_ID (MAIL_ID)
		) TYPE = MYISAM  DEFAULT CHARSET=utf8;";
$result2 = $wpdb->query($sql2);

add_option('favorite_mail_to', get_option('admin_email') );
add_option('favorite_mail_msg_fail', "<p>Failed sending to e-mail address.</p>");
add_option('favorite_mail_msg_sent', "<p>Request Sent.</p>");

}




if(isset($_GET["post_id"])) {
add_action('init', 'favorite_post_modify'); // calls function my_fav_quote_modify_database() at the initialisation of each page
}

function favorite_post_modify(){
	global $favorite_mail_cookie,$table_mail_post_rel,$table_mail_content,$wpdb;
	$post_id = $_GET['post_id'];
	if (isset($_COOKIE["favorite_mail_cookie"])){
             $favorite_mail_cookie = $_COOKIE["favorite_mail_cookie"];
	}else{
		$timestamp = time(); 
		$val = $timestamp . '' . rand(0,9);
		$expire=time()+60*60*24*30;
		setcookie("favorite_mail_cookie", $val, $expire);
		$favorite_mail_cookie = $_COOKIE["favorite_mail_cookie"];
	}
	$sql = 'SELECT * FROM ' . $table_mail_post_rel . ' WHERE post_id = ' . $post_id . ' and cookie = "' . $favorite_mail_cookie . '" ;';
		$data = $wpdb->get_results($sql);
	        $postData = $data[0]->post_id;

		if(isset($post_id)){
			if($postData == ""){
				$wpdb->query("INSERT INTO $table_mail_post_rel (post_id,cookie) VALUES ('$post_id','$favorite_mail_cookie')");
			}
		}
}
/*保存email*/
function favorite_mail_insert(){
	global $favorite_mail_cookie,$table_mail_post_rel,$table_mail_content,$wpdb;
	$name = stripslashes($_POST['name']);
	$email = stripslashes($_POST['email']);
	$content = stripslashes($_POST['content']);
	$post_id = stripslashes($_POST['post_id']);
        $sql='INSERT INTO ' . $table_mail_content . ' (IP,NAME,EMAIL,CONTENT) VALUES ("' . favorite_getip() .'","' . $name . '" ," ' . $email . '","' . $content . '")';
	echo $sql;
	$wpdb->query($sql);
	$mail_id = mysql_insert_id();
	$sql = ' UPDATE ' . $table_mail_post_rel . ' SET MAIL_ID =' . $mail_id . ' WHERE post_id in ( ' . $post_id . ' ) and cookie = "' . $_COOKIE["favorite_mail_cookie"] . '" '; 
	$wpdb->query($sql);
	
}

function favorite_getip() {
	if (isset($_SERVER)) {
		if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
			$ip_addr = $_SERVER["HTTP_X_FORWARDED_FOR"];
		} 
		elseif (isset($_SERVER["HTTP_CLIENT_IP"])) {
			$ip_addr = $_SERVER["HTTP_CLIENT_IP"];
		} 
		else {
			$ip_addr = $_SERVER["REMOTE_ADDR"];
		}
	} 
	else {
		if ( getenv( 'HTTP_X_FORWARDED_FOR' ) ) {
			$ip_addr = getenv( 'HTTP_X_FORWARDED_FOR' );
		} 
		elseif ( getenv( 'HTTP_CLIENT_IP' ) ) {
			$ip_addr = getenv( 'HTTP_CLIENT_IP' );
		} 
		else {
			$ip_addr = getenv( 'REMOTE_ADDR' );
		}
	}
	
	return $ip_addr;
}# end my_fav_quote_show_optin_form
# ----------------------------------
#  general settings
function favorite_mail_settings() {

	global $favorite_mail_cookie,$table_mail_post_rel,$table_mail_content,$wpdb;

	
	// Get current options from database
	$email_to = stripslashes(get_option('favorite_mail_to'));
	$msg_fail = stripslashes(get_option('favorite_mail_msg_fail'));
	$msg_sent = stripslashes(get_option('favorite_mail_msg_sent'));

	//// Update options if user posted new information
	if( $_POST['process'] == 'edit' ) {
		// Read from to 
		$email_to = stripslashes($_POST['favorite_mail_to']);
		$msg_fail = stripslashes($_POST['favorite_mail_msg_fail']);
		$msg_sent = stripslashes($_POST['favorite_mail_msg_sent']);
		// Save to database
		update_option('favorite_mail_to', $email_to );
		update_option('favorite_mail_msg_fail', $msg_fail);
		update_option('favorite_mail_msg_sent', $msg_sent);
		//notify change
		echo '<div id="message" class="updated fade"><p><strong>';
		_e('Settings saved.', 'favorite_mail_domain');
		echo '</strong></p></div>';
	}
	if( $_POST['process'] == 'send-mail' ) {
		$content = stripslashes($_POST['content']);
		$mailTo = spliti (',' , $email_to);
		//var_dump($mailTo);
		//exit;	
		wp_mail($mailTo,'test from favorite',$content,'4756088@qq.com');
		global $phpmailer;
		if ( $phpmailer->ErrorInfo != "" ) {
			echo $phpmailer->ErrorInfo ;
		} else {
			favorite_mail_insert();
			echo $msg_sent;
		}
	}	

       $sql = 'SELECT name, email, content FROM ' . $table_mail_content . ' ORDER BY CREATED_DATE desc ';
       $favorite_list = $wpdb->get_results($sql);

?>
<div class="favorite_mail_list">
<table class="wp-list-table widefat">
<thead>
  <tr>
    <th>姓名</th>
    <th>邮箱</th>
    <th>内容</th>
    <th>操作</th>
  </tr>
</thead>
<tbody>
  <?php
foreach ($favorite_list as $entry){
  ?>
  <tr>
  <td><?php echo  $entry->name ;?> </td>
    <td><?php echo   $entry->email;?></td>
    <td><?php echo   $entry->content ;?></td>
    <td><a href="#" class="product-detail">product detail</a></td>
  </tr>
   <?php 
	}
?>
</tbody>
</table>

</div>

<div class="favorite-mail-settings">
<h2>Favorite mail</h2>
<form method="post" action="#">
    <input type="hidden" name="process" value="edit" />
    <table widtd="100%" cellspacing="2" cellpadding="2">
	<tr valign="top"> 
        <td scope="row" colspan=2><p class="title">General Settings</p></td>
      </tr>
      <tr valign="top"> 
        <td scope="row">Send To (email address)</td>
        <td> 
            <input type="text" name="favorite_mail_to" id="favorite_mail_to" value="<?php echo $email_to; ?>" size="40" /> <span>If you send more than one please "," was separated</span>
        </td>
      </tr>
      <tr valign="top"> 
        <td scope="row">Failed to send email:</td>
        <td> 
          <input type="text" name="favorite_mail_msg_fail" id="favorite_mail_msg_fail" value="<?php echo $msg_fail; ?>" size="40" />
        </td>
      </tr>
      <tr valign="top"> 
        <td scope="row">Success send email:</td>
        <td> 
          <input type="text" name="favorite_mail_msg_sent" id="favorite_mail_msg_sent" value="<?php echo $msg_sent; ?>" size="40" />
        </td>
      </tr>
    </table>
    <p class="submit"><input type="submit" name="Submit" value="Update Settings" /></p>
</form>


<div class="test">
<form name="configure_smtp" action="#" method="post">
<input type="hidden" name="process" value="send-mail" />
text :<textarea type="text" name="content" id="content" rows="5" cols="45" >test from favorite mail</textarea>
<input name="name" value="1625" type="text" />
<input name="post_id" value="5" type="text" />
<input name="email" value="420071845@qq.com" type="text" />
<div class="submit"><input type="submit" name="Submit" value="test" /></div>
</form>
<form name="configure_smtp" action="" method="get">
<input type="text" name="post_id" value="5" />
<div class="submit"><input type="submit" name="Submit" value="add favorite" /></div>
</form>
</div>
</div>

<?php 





}# end my_fav_quote_settings
//add_filter('the_content','favorite_mail_settings',1,1000);

function favorite_mail_menu() {
	add_options_page('Favorite mail', 'Favorite mail', 6, __FILE__, 'favorite_mail_settings' );
}

//add_shortcode('addquote', 'add_favorite_quotes');
//
//

	function send_test_form() {
	
	}
